var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
var async = require("async");
var DB = require("../../model/db");

var host = "";
router.use(function (req, res, next) {
    Host = "http://" + req.headers.host;
    next();
})

router.get('/', function (req, res) {
    var page = req.query.page;
    if (!page) {
        page = 1;
    }
    async.parallel({
        count: function (callback) {
            DB.count("order", {}, function (err, data) {
                callback(err, data)
            })
        },
        order: function (callback) {
            DB.find("order", {},{order_id: 1, product_title: 1,  add_time: 1, status: 1, username: 1, tel: 1},{ pageSize: 10, page: page }, function (err, data) {
                callback(err, data)
            })
        }
    }, function (err, data) {
        res.render("admin/order/index", {
            host: Host,
            list: data.order,
            totalPages: Math.ceil(data.count / 10),
            page:page
        })
    })
});


router.get("/edit/:id",function(req,res){
    var id = req.params.id;
    DB.find("order", { "_id": new DB.ObjectID(id) }, function (err, data) {
        if (err) {
            console.log(err);
            return;
        } else {
            res.render("admin/order/edit", {
                host: Host,
                list: data[0]
            })
        }
    })
})

router.post("/editPost",function(req,res){
    var form = new multiparty.Form();
    form.uploadDir = "./public/resource";
    form.parse(req, function (err, fields, files) {
        var id = fields.id[0];
        var order_id = fields.order_id[0];
        var product_title = fields.product_title[0];
        var count = fields.count[0];
        var price = fields.price[0];
        var all_price = fields.all_price[0];
        var add_time = fields.add_time[0];
        var status = fields.status[0];
        var username = fields.username[0];
        var tel = fields.tel[0];
        var address = fields.address[0];

        DB.updateOne("order", { "_id": new DB.ObjectID(id) },{order_id:order_id,product_title:product_title,count:count,price:price,all_price:all_price,add_time:add_time,status:status,username:username,tel:tel,address:address}, function (err, result) {
            if (err) {
                console.log(err);
                return;
            } else {
                res.send('<script>alert("修改成功");location.href="/admin/order"</script>');
            }
        })
    })
})

router.get("/delete/:id",function(req,res){
    var id = req.params.id;
    DB.deleteMany("order", { "_id": new DB.ObjectID(id) }, function (err, result) {
        if (err) {
            console.log(err);
            return;
        } else {
            res.redirect(Host + "/admin/order");
        }
    })
})

module.exports = router;